import * as types from './mutation-types'

export default {
  [types.SET_CURRENT_TICKET_TAB] (state, newTab) {
    state.currentTicketTab = newTab
  },

  [types.ADD_TICKET_TAB] (state, payload) {
    const { type, ticket } = payload
    const alreadyExists = checkIfExists(ticket, state.opendTicketTabs[type])

    if (!alreadyExists) {
      state.opendTicketTabs[type].push(ticket)
      setLocalTicketTabs(state)
    }
  },

  [types.REMOVE_TICKET_TAB] (state, payload) {
    const { type, ticketId } = payload
    state.opendTicketTabs[type] = state.opendTicketTabs[type].filter(item => item.id !== +ticketId)

    state.currentTab = 'list'
    setLocalTicketTabs(state)
  },

  [types.CLEAR_TICKET_TAB] (state) {
    state.opendTicketTabs = { detail: [], edit: [] }
    state.currentTab = 'list'
    setLocalTicketTabs(state)
  },

  [types.RECEIVE_ALL_CITIES] (state, cities) {
    state.allCities = cities
  }
}

function setLocalTicketTabs ({ opendTicketTabs }) {
  sessionStorage.setItem('opendTicketTabs', JSON.stringify(opendTicketTabs))
}

function checkIfExists (ticket, arr) {
  return arr.some(item => item.id === ticket.id)
}
